// ControllerLib.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "ControllerLib.h"


bool ReadHexFile(string path)
{

	ifstream ifs(path);
	while(ifs.eof()==false)
	{
		string line;
		getline(ifs,line);
		if(ParseHexLine(line)==false)
		{
			ifs.close();
			return false;
		}

	}
	ifs.close();
	return true;

}

bool ReadDatFile(string path)
{
	ifstream ifs(path);
	memset(dataBuff,0,MAXSIZE);
	char hex[3];
	hex[2]='\0';
	char* pBuffer = dataBuff;
	while(ifs.eof()==false)
	{
		ifs.read(hex,2);
		*pBuffer++=Hex2Dec(hex);
	}

	ifs.close();
	return true;
}

bool ParseHexLine(string line)
{
	int size,address,type,data,checksum;
	size=address=type=data=checksum=0;
	int sum=0;

	if(line.length()<10)
	{
		return false;
	}

	// parse Intel hex file
	/** StartCode|ByteCount|Address|RecordType(data:0)|Data|CheckSum **/
	// example :|10|05C4|00|CAC290B1CA227C037DFF7EFFDEFEDDFA|43

	int i=0; // parse index
	// StartCode
	if(line[i]!=':')
	{
		return false;
	}
	i++;

	// ByteCount
	size= Hex2Dec(line.substr(i,2));

	if(size<0)
	{
		return false;
	}
	i+=2;
	sum+=size;

	// Address
	int t = i;
	sum+=Hex2Dec(line.substr(t,2));
	t+=2;
	sum+=Hex2Dec(line.substr(t,2));
	address=Hex2Dec(line.substr(i,4));
	if(address<0||address>MAXSIZE||(address+size)>MAXSIZE)
	{
		return false;
	}
	i+=4;

	// RecordType
	type=Hex2Dec(line.substr(i,2));
	// we only address data section
	if(type>1)
	{
		return false;
	}
	if(type==1)
	{
		return true;// we just do nothing for configuration
	}
	i+=2;
	sum+=type;

	// Data
	char* pBuffer = dataBuff+address;
	
	for(int j=0;j<size;j++)
	{
		data = Hex2Dec(line.substr(i,2));
		*pBuffer++=data;
		sum+=data;
		i+=2;
	}

	// CheckSum
	checksum = Hex2Dec(line.substr(i,2));

	sum=sum&0xff;
	sum = 0x100-sum;
	if(checksum!=sum)
	{
		return false;
	}

	return true;

}

 CONTROLLERLIB_API bool __stdcall GetExternData(int nZone,unsigned long lunSize,BYTE* byBuff)
{
	// ReadHexFile("extend.dat");
	ReadDatFile("externd.dat");
	 switch(nZone){
        case 0:
                for(unsigned long i=0;i<lunSize;i++)
					 byBuff[i] = dataBuff[i];
                break;
   }
   return true;

}


 CONTROLLERLIB_API char* GetDataBuffer(char* path)
{
	ReadHexFile(path);
	return dataBuff;
}
